package com.filter;

import com.alibaba.fastjson.JSONObject;
import com.comm.JwtResult;
import com.comm.R;
import com.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.UUID;

/**
 * token续签：可以采用双token认证的方式 一个current_token 一个refresh_token
 *
 * current_token：在登录接口，登录成功的话就生成两个token  一个current_token 一个 refresh_token，两个token生成的条件，签名，时间都保持一致
 * 在shiro拦截器里的拦截方法中，验证current_token，如果没过期则刷新一个refresh_token
 * 如果过期了   则验证refresh_token   如果过期了，那么拦截，如果不过期，那么使current_token和refresh_token都刷新一遍 再重新写给前端，拦截器返回true
 */
public class OAuth2Filter extends AuthenticatingFilter {
    //暂时不重写createToken方法
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return null;
    }
    //是访问允许
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;


    }

    //访问拦截
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        String currentToken = request.getHeader("current_Authorization");
        String refreshToken=request.getHeader("refresh_Authorization");
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        Session session = subject.getSession();
        Serializable id = session.getId();
        System.out.println("session_id:-----"+id.toString());
        if (currentToken==null||"".equals(currentToken)||principal==null){
            R resultData = R.defaulted().setMsg("未登录！  不合法的验证");
            response.getWriter().write(JSONObject.toJSONString(resultData));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        JwtResult jwtResult = JwtUtils.validateJwt(currentToken);
        if (jwtResult.isSuccess()){//合法
           /* //解析token
            Claims claims = JwtUtils.parseJWT(token);//token中的获得用户名 和 密码
            //解析token获得getSubject
            UsernamePasswordToken usernamePasswordToken = JSONObject.parseObject(claims.getSubject(),UsernamePasswordToken.class);
            //执行登录
            getSubject(request,response).login(usernamePasswordToken);*/
            //执行登录 没有抛异常，就证明成功
/*
            JwtUtils.createJwt(UUID.randomUUID().toString(),JwtUtils.JWT_SECERT,)
*/          currentToken=refreshToken;
            refreshToken=JwtUtils.createJwt(UUID.randomUUID().toString(),JwtUtils.JWT_SECERT,principal.toString(),JwtUtils.TTMILLIS);
            response.addHeader("current_Authorization",currentToken);
            response.addHeader("refresh_Authorization",refreshToken);
            return true;

        }else{//不合法
            //3. token过期
            R r = R.defaulted();
            if(jwtResult.getErrCode() == JwtUtils.JWT_ERRCODE_EXPIRE){
                r.setCode(jwtResult.getErrCode());
                r.setMsg("token 过期"+"用户：----"+principal.toString());
            }
            //4. token不合法
            if(jwtResult.getErrCode() == JwtUtils.JWT_ERRCODE_FAIL){
                r.setCode(jwtResult.getErrCode());
                r.setMsg("token 不合法"+"用户：----"+principal.toString());
            }
            response.getWriter().write(JSONObject.toJSONString(r));
            response.getWriter().flush();
            response.getWriter().close();
            return  false;
        }

    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            R r = R.defaulted();
            r.setCode(401);
            r.setMsg(throwable.getMessage());
            String json = JSONObject.toJSONString(r);
            httpResponse.getWriter().print(json);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
